/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   09.05.2010
 * @version SVN: $Id: BaseProductToProductAdapter.java 123 2010-05-11 20:18:31Z christian-kerl@web.de $
 */
package org.cakis.server.service.util;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.cakis.server.model.*;

/**
 * BaseProductToProductAdapter marshals {@link BaseProduct} instances to
 * {@link Product}. {@link Product#getEanNumber()} == null is used as
 * type discriminator.
 *
 * @author Christian Kerl
 */
public class BaseProductToProductAdapter extends XmlAdapter<Product, BaseProduct> {

    @Override
    public Product marshal(BaseProduct v) throws Exception {
        Product result = null;

        if(v instanceof Product) {
            result = (Product) v;
        } else if(v instanceof ProductType) {
            ProductType type = (ProductType) v;

            result = new Product();
            result.setId(type.getId());
            result.setName(type.getName());
        } else {
            throw new IllegalArgumentException("Unsupported BaseProduct implementation!");
        }

        return result;
    }

    @Override
    public BaseProduct unmarshal(Product v) throws Exception {
        BaseProduct result = v;

        if(v.getEanNumber() == null) {
            // sanity check
            if(v.getStandardQuantity().getUnit() != null) {
                throw new IllegalArgumentException("Illegal Product state: EanNumber is null, but StandardQuantity.Unit is not null!");
            }

            result = new ProductType();
            result.setId(v.getId());
            result.setName(v.getName());
        }

        return result;
    }

}
